package spring.boot.admin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import spring.boot.admin.handler.RedisOneChannelOneHandler;
import spring.boot.admin.handler.RedisOneChannelTwoHandler;
import spring.boot.admin.handler.RedisTwoChannelOneHandler;
import spring.boot.admin.handler.RedisTwoChannelTwoHandler;


/**
 * redis 消息发布订阅的监听器配置
 * 有两个数据源 one 和  two ，每个数据源有两个channel
 * 这里的四个队列互不影响，各自订阅各自的消息
 * 四个handler分别是四个channel的消息处理器，每个处理器需要继承  MessageListenerAdapter类
 */
@Configuration
public class RedisChannelConfig {

    @Autowired
    private RedisOneChannelOneHandler redisOneChannelOneHandler;

    @Autowired
    private RedisOneChannelTwoHandler redisOneChannelTwoHandler;

    @Autowired
    private RedisTwoChannelOneHandler redisTwoChannelOneHandler;

    @Autowired
    private RedisTwoChannelTwoHandler redisTwoChannelTwoHandler;

    @Bean
    public RedisMessageListenerContainer redisOneContainer(@Qualifier("oneLettuceConnectionFactory") RedisConnectionFactory oneLettuceConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(oneLettuceConnectionFactory);
        //根据queue调用,多个channel这里可以add多个
        container.addMessageListener(redisOneChannelOneHandler, new PatternTopic(redisOneChannelOneHandler.getChannel()));
        container.addMessageListener(redisOneChannelTwoHandler, new PatternTopic(redisOneChannelTwoHandler.getChannel()));
        return container;
    }


    @Bean
    public RedisMessageListenerContainer redisTwoContainer(@Qualifier("twoLettuceConnectionFactory") RedisConnectionFactory twoLettuceConnectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(twoLettuceConnectionFactory);
        //根据queue调用,多个channel这里可以add多个
        container.addMessageListener(redisTwoChannelOneHandler, new PatternTopic(redisTwoChannelOneHandler.getChannel()));
        container.addMessageListener(redisTwoChannelTwoHandler, new PatternTopic(redisTwoChannelTwoHandler.getChannel()));
        return container;
    }

}
